import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate, Link } from 'react-router-dom';
import { Layout, Menu, Button } from 'antd';
import { UserOutlined, ShoppingCartOutlined, BarChartOutlined, TeamOutlined, MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import Ranking from './pages/Ranking';
import OrderList from './pages/OrderList';
import UserManagement from './pages/UserManagement';
import Login from './components/Login';
import Register from './components/Register';
import { authAPI } from './services/api';
import './App.css';
import UserDashboard from './pages/UserDashboard';

const { Header, Content, Sider } = Layout;

function App() {
    const [isAuthenticated, setIsAuthenticated] = useState(false);
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);
    const [collapsed, setCollapsed] = useState(false);

    useEffect(() => {
        console.log('App mounted, checking authentication');
        const token = localStorage.getItem('token');
        const userData = localStorage.getItem('user');
        
        if (token && userData) {
            console.log('Found token and user data in localStorage');
            try {
                const parsedUser = JSON.parse(userData);
                console.log('Parsed user data:', parsedUser);
                setUser(parsedUser);
                setIsAuthenticated(true);
            } catch (error) {
                console.error('Error parsing user data:', error);
                localStorage.removeItem('token');
                localStorage.removeItem('user');
            }
        } else {
            console.log('No token or user data found in localStorage');
        }
        setLoading(false);
    }, []);

    const handleLogin = async (credentials) => {
        console.log('Attempting login with credentials:', {
            username: credentials.username,
            passwordLength: credentials.password?.length
        });
        
        try {
            console.log('Calling authAPI.login...');
            const response = await authAPI.login(credentials);
            console.log('Login API response:', {
                status: response.status,
                hasData: !!response.data,
                hasToken: !!response.data?.token,
                hasUser: !!response.data?.user
            });

            if (response.data && response.data.token) {
                console.log('Login successful, updating state with user:', response.data.user);
                setIsAuthenticated(true);
                setUser(response.data.user);
                
                // 验证状态是否正确设置
                console.log('Verifying authentication state:', {
                    isAuthenticated: true,
                    user: response.data.user
                });
                
                return true;
            }
            
            console.log('Login failed: missing token or user data in response');
            return false;
        } catch (error) {
            console.error('Login error:', {
                message: error.message,
                response: {
                    status: error.response?.status,
                    data: error.response?.data
                }
            });
            return false;
        }
    };

    const handleLogout = () => {
        console.log('Logging out');
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        setIsAuthenticated(false);
        setUser(null);
    };

    if (loading) {
        return <div className="loading">加载中...</div>;
    }

    console.log('Current auth state:', { isAuthenticated, user });

    if (!isAuthenticated) {
        return (
            <Router>
                <Routes>
                    <Route path="/login" element={<Login onLogin={handleLogin} />} />
                    <Route path="/register" element={<Register />} />
                    <Route path="*" element={<Navigate to="/login" />} />
                </Routes>
            </Router>
        );
    }

    return (
        <Router>
            <Layout style={{ minHeight: '100vh' }}>
                <Header className="header">
                    <div className="logo">Yaksa女团管理平台</div>
                    <div className="user-info">
                        <span>欢迎, {user?.username}</span>
                        <Button type="link" onClick={handleLogout}>
                            退出登录
                        </Button>
                    </div>
                </Header>
                <Layout>
                    <Sider 
                        width={200} 
                        className="site-layout-background"
                        collapsible
                        collapsed={collapsed}
                        onCollapse={setCollapsed}
                        trigger={null}
                    >
                        <div className="menu-collapse-button">
                            {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
                                className: 'trigger',
                                onClick: () => setCollapsed(!collapsed),
                            })}
                        </div>
                        <Menu
                            mode="inline"
                            defaultSelectedKeys={['1']}
                            style={{ height: '100%', borderRight: 0 }}
                            inlineCollapsed={collapsed}
                        >
                            {user?.permission === 'admin' ? (
                                <>
                                    <Menu.Item key="1" icon={<BarChartOutlined />}>
                                        <Link to="/ranking">排名统计</Link>
                                    </Menu.Item>
                                    <Menu.Item key="2" icon={<ShoppingCartOutlined />}>
                                        <Link to="/orders">订单管理</Link>
                                    </Menu.Item>
                                    <Menu.Item key="3" icon={<TeamOutlined />}>
                                        <Link to="/users">用户管理</Link>
                                    </Menu.Item>
                                </>
                            ) : (
                                <>
                                    <Menu.Item key="1" icon={<BarChartOutlined />}>
                                        <Link to="/ranking">排名统计</Link>
                                    </Menu.Item>
                                    <Menu.Item key="2" icon={<ShoppingCartOutlined />}>
                                        <Link to="/orders">订单管理</Link>
                                    </Menu.Item>
                                    <Menu.Item key="3" icon={<UserOutlined />}>
                                        <Link to="/user">个人资料</Link>
                                    </Menu.Item>
                                </>
                            )}
                        </Menu>
                    </Sider>
                    <Layout style={{ padding: '24px' }}>
                        <Content
                            className="site-layout-background"
                            style={{
                                padding: '24px',
                                margin: 0,
                                minHeight: 280,
                                background: '#fff',
                                borderRadius: '4px',
                            }}
                        >
                            <Routes>
                                <Route path="/" element={<Navigate to="/orders" />} />
                                <Route path="/ranking" element={<Ranking />} />
                                <Route path="/orders" element={
                                    user?.permission === 'admin' ? 
                                        <OrderList /> : 
                                        <OrderList readOnly />
                                } />
                                <Route path="/user" element={<UserDashboard />} />
                                <Route path="/users" element={
                                    user?.permission === 'admin' ? 
                                        <UserManagement /> : 
                                        <Navigate to="/" />
                                } />
                            </Routes>
                        </Content>
                    </Layout>
                </Layout>
            </Layout>
        </Router>
    );
}

export default App;